import { createRouter, createWebHistory } from 'vue-router';
import { authGuard, guestGuard } from './guards';

import layout from '@/views/layout/index.vue';
import login from '@/views/login/index.vue';
import home from '@/views/layout/Home.vue';
import forum from '@/views/layout/Forum.vue';
import payment from '@/views/layout/Payment.vue';
import travel from '@/views/layout/travel.vue';
import visa from '@/views/layout/visa.vue';
import profile from '@/views/profile/index.vue';
import orders from '@/views/orders/index.vue';
import settings from '@/views/settings/index.vue';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: home,
      meta: {
        title: '首页',
        requiresAuth: false, // 不需要身份验证
      }
    },
    {
      path: '/login',
      component: login,
      meta: {
        title: '登录/注册',
        guest: true, // 仅限游客访问
      }
    },
    {
      path: '/profile',
      component: profile,
      meta: {
        title: '个人资料',
        requiresAuth: true, // 需要身份验证
      }
    },
    {
      path: '/forum',
      component: forum,
      meta: {
        title: '旅游论坛',
        requiresAuth: false, // 不需要身份验证
      }
    },
    {
      path: '/payment',
      component: payment,
      meta: {
        title: '支付',
        requiresAuth: true, // 需要身份验证
      }
    },
    {
      path: '/travel',
      component: travel,
      meta: {
        title: '旅游',
        requiresAuth: false, // 不需要身份验证
      }
    },
    {
      path: '/visa',
      component: visa,
      meta: {
        title: '签证信息',
        requiresAuth: false, // 明确设置不需要身份验证
      }
    },
    {
      path: '/orders',
      component: orders,
      meta: {
        title: '我的订单',
        requiresAuth: true, // 需要身份验证
      }
    },
    {
      path: '/settings',
      component: settings,
      meta: {
        title: '设置',
        requiresAuth: true, // 需要身份验证
      }
    },
    {
      path: '/dashboard',
      component: layout,
      meta: {
        title: '控制面板',
        requiresAuth: true, // 需要身份验证
      }
    },
    {
      path: '/:pathMatch(.*)*', // 匹配所有未定义的路由
      component: login,
      meta: {
        title: '页面不存在',
      }
    }
  ]
});

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 旅行网站` : '旅行网站';
  
  // 验证身份认证
  if (to.meta.requiresAuth) {
    return authGuard(to, from, next);
  }
  
  // 验证游客状态
  if (to.meta.guest) {
    return guestGuard(to, from, next);
  }
  
  // 其他情况直接放行
  next();
});

export default router;